package http.secure.common.config;

import http.secure.common.constant.SecureProperties;
import http.secure.common.keys.validator.RepeatValidator;
import http.secure.common.keys.validator.impl.MappedRepeatValidator;
import http.secure.common.keys.validator.impl.RedisRepeatValidator;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.File;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class RepeatValidatorConfig {
    private final SecureProperties properties;

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(name = "spring.data.redis.host")
    public RepeatValidator redisRepeatValidator(StringRedisTemplate template) {
        log.info("Redis repeat validator is enable");
        return new RedisRepeatValidator(template, properties);
    }

    @Bean
    @ConditionalOnMissingBean
    public RepeatValidator repeatValidator() {
        log.info("Mapped repeat validator is enable");
        File cache = new File(System.getProperty("java.io.tmpdir"), "MapRepeatValidatorData");
        return new MappedRepeatValidator(cache, properties);
    }
}
